/*
 * @Author: hanyu 
 * @Date: 2018-05-09 11:08:25 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2019-01-04 11:03:51
 */
<template>
  <div>
    <chart
      id="myBarCharts"
      :noData="noData"
      :chartStyle="chartStyle ? chartStyle : 'min-height:230px;height:300px'"
      :option="dataOption"
    />
  </div>
</template>
<script>
import chart from "./newChart";
import echarts from "echarts";
import _ from "lodash";
/*
多个bar图表
value:[{
    name:'',
    value:'',
    color:[],
}]
option:{ //echart 的 option
    showBarNum:2, // 显示柱数量，
    showTooltipNum:4 // 默认显示hover数量
    legendArr:['',''] //如果有legend ,按照顺序传入 legend 名字
    hideLineColor:false  //是否显示渐变色，默认渐变色
    color:[] ,// 需要 hideLineColor:true 时候才生效
    startColor:[], // 只有两组数据的时候才会生效
    barBorderRadius: [],//柱状图 的圆角设置， 只有两组数据的时候才会生效
    endColor: [],// 只有两组数据的时候才会生效
    unit:'' //【】，//单位
    labelDefault: 0 ,// 显示 label 的柱状图（数据组别）
    showLabel: false ,// 不显示 label ）
}
*/
var hideLineColor = false; // 是否隐藏 渐变色
const lineColor = [
  // 线性渐变
  {
    startColor: "#00d1ff",
    endColor: "#0c43fd"
  },
  {
    startColor: "#3a6dff",
    endColor: "#663bfe"
  }
];
const color = [
  "#28e787",
  "#00d1ff",
  "#3771ff",
  "#8d4cfd",
  "#28e787",
  "#00d1ff",
  "#3771ff",
  "#8d4cfd"
];
export default {
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      }
    },
    option: {
      type: Object,
      default: () => {
        return {};
      }
    },
    chartStyle: {
      type: String, // 自定义图标宽高
      default: () => {
        return "";
      }
    }
  },
  components: {
    chart
  },
  data() {
    return {
      dataOption: {},
      noData: false
    };
  },
  watch: {
    value(newValue) {
      if (newValue.length === 0) {
        this.noData = true;
      } else {
        this.noData = false;
        var newArr = [];
        newValue.forEach(element => {
          newArr.push({
            list: element.list.slice(0, this.option.showBarNum || 2),
            name: element.name
          });
        });
        this.setOption(newArr, newValue);
      }
    }
  },
  methods: {
    setOption(res, res2) {
      var xData = [];
      var allData = [];
      var self = this;
      var length = res[0].list.length;
      if (length === 0) {
        this.noData = false;
        return;
      }
      var legend = [];
      // 数组大于2 不用渐变色
      if (length > 2) {
        hideLineColor = true;
      } else {
        hideLineColor = false;
      }
      for (let i = 0; i < length; i++) {
        var legendIcon = "circle";
        const data = {
          type: "bar",
          name: "",
          label: {
            normal: {
              show: false, // 去掉柱状图上方的数值。
              position: "top",
              distance: 8, // 距离图形的距离
              textStyle: {
                color: this.option.color || "#00d1ff",
                fontWeight: "bold",
                fontFamily: "DIN Condensed Bold",
                fontSize: "16"
              }
            }
          },
          // itemStyle: {
          //   normal: !hideLineColor && {
          //     barBorderRadius: this.option.barBorderRadius || [0, 0, 0, 0],
          //     color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
          //       {
          //         offset: 0,
          //         color: this.option.startColor[i] || lineColor[i].startColor
          //       },
          //       {
          //         offset: 1,
          //         color: this.option.endColor[i] || lineColor[i].endColor
          //       }
          //     ])
          //   }
          // },
          z: 10,
          data: [],
          barWidth: 21
        };
        if (i === Number(this.option.labelDefault)) {
          data.label.normal.show = false; // 去掉柱状图上方的数值。
        } else {
          data.label.normal.show = this.option.showLabel || false;
        }
        if (i === 0) {
          // data.barCategoryGap = 2;
          // data.barGap = barWidth / 2;
        }
        var legendItem = {
          name: "",
          textStyle: {
            color: "#31cee6",
            icon: legendIcon,
            fontSize: 14,
            padding: 0
          }
        };
        data.name = res[0].list[i].name || res[0].list[i].xData || "";
        legendItem.name = res[0].list[i].name || res[0].list[i].xData || "";
        legendItem.icon = legendIcon;
        legend.push(legendItem);
        allData.push(data);
      }
      allData.forEach((dataItem, itemId) => {
        res.forEach(listItem => {
          if (itemId === 0) {
            const itemXData =
              listItem.name || listItem.xData || listItem.xData1;
            xData.push(itemXData);
          }
          if (Number(listItem.list[itemId].value) < 0) {
            allData[itemId].label.normal.position = "bottom";
          } else {
            allData[itemId].label.normal.position = "top";
          }
          dataItem.data.push(listItem.list[itemId].value);
        });
      });

      /* 计算barWidth*/
      var xLength = xData.length; // x轴数据
      var oneXLegth = allData.length; // 一个x周坐标 有几条柱状图 （有几组数据） 数据类目
      var myChartW = document.getElementById("myBarCharts").offsetWidth;
      var yAxisW = 0; // 左边轴距左边容器的宽度
      var grid = {
        right: 0,
        left: 0,
        bottom: 0
      };
      grid.left =
        this.option.grid && this.option.grid.left
          ? this.option.grid.left
          : "10%";
      grid.bottom =
        this.option.grid && this.option.grid.bottom
          ? this.option.grid.bottom
          : ((100 / myChartW) * 100).toFixed(2) + "%";
      var gridNum = Number(grid.left.replace("%", "")) / 100;
      yAxisW = myChartW * gridNum;
      myChartW = myChartW - yAxisW;
      // var 大间隙 = 柱子宽度
      // [柱子宽度 * 数据类目 + 2（数据类目 -1）+ 柱子宽度 * 数据类目 + 2（数据类目 -1）] * x轴坐标数 = x轴长度
      var fenzi = myChartW / xLength / 2 - [2 * (oneXLegth - 1)];
      var fenmu = oneXLegth + 1;
      var barWidth = Math.round(fenzi / fenmu);
      /* 计算barWidth 结束*/
      allData.forEach(item => {
        item.barWidth = self.option.barWidth || barWidth;
      });

      var option = {
        color: hideLineColor ? color : [],
        dataZoom: [
          {
            show: false,
            bottom: 87,
            height: 6,
            zoomLock: true,
            xAxisIndex: [0],
            start: 0,
            right: 0,
            handleIcon:
              "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
            handleSize: "120%",
            backgroundColor: "#31cee6",
            borderColor: "#3F79F6",
            fillerColor: "#3F79F6",
            handleStyle: {
              color: "#3F79F6",
              opacity: 0
            },
            textStyle: {
              color: "#3F79F6"
            }
          }
        ],
        xAxis: {
          data: xData,
          axisLabel: {
            rotate: 45,
            formatter: function(value) {
              return "{value|" + value + "}";
            }
          }
        },
        yAxis: {
          name: this.option.unit ? this.option.unit[0] : "",
          nameGap: 30,
          nameTextStyle: {
            color: "#31cee6"
          },
          axisLabel: {
            margin: 2,
            formatter: value => this.$utils.formatterAxisLabel(value)
          }
        },
        legend: {
          data: legend,
          itemGap: 10,
          top: "bottom",
          bottom: "36",
          orient: "horizontal"
        },
        tooltip: {
          axisPointer: {
            shadowStyle: {
              color: {
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(0,0,0,0)" // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(0,209,255,0.2)" // 100% 处的颜色
                  }
                ]
              }
            }
          },
          formatter: params =>
            this.$utils.newFormatterLine(res2, params, this.option.unit)
        },
        grid: {
          bottom: "100",
          left: "10%",
          right: 0
        },
        series: allData
      };
      if (this.option.showTooltipNum === 4) {
        option.tooltip = {
          axisPointer: {
            shadowStyle: {
              color: {
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(0,0,0,0)" // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(0,209,255,0.2)" // 100% 处的颜色
                  }
                ]
              }
            }
          },
          formatter: params =>
            this.$utils.newFormatterLine(res2, params, this.option.unit)
        };
      } else if (this.option.showTooltipNum === 3) {
        option.tooltip = {
          axisPointer: {
            shadowStyle: {
              color: {
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(0,0,0,0)" // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(0,209,255,0.2)" // 100% 处的颜色
                  }
                ]
              }
            }
          },
          formatter: params =>
            this.$utils.threeDataFormatterLine(res2, params, this.option.unit)
        };
      } else {
        option.tooltip = {
          axisPointer: {
            shadowStyle: {
              color: {
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(0,0,0,0)" // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(0,209,255,0.2)" // 100% 处的颜色
                  }
                ]
              }
            }
          },
          formatter: params =>
            this.$utils.formatterLine(res, params, this.option.unit)
        };
      }
      if (barWidth < 5) {
        option.dataZoom[0].show = true;
        option.dataZoom[0].end = (20 / xLength) * 100;
      } else {
        option.dataZoom[0].show = false;
        option.dataZoom[0].end = 100;
      }
      var allOption = _.merge(option, this.option);
      if (this.option.markLine) {
        allOption.series[0].markLine = this.option.markLine;
      }
      this.noData = false;
      this.$set(this, "dataOption", allOption);
    }
  }
};
</script>

<style scoped>
.noData {
  color: white;
  text-align: center;
  font-size: 20px;
  margin-top: 50px;
}
</style>